package com.service.impl;

import com.dto.LoginRequest;
import com.dto.LoginResponse;
import com.entity.User;
import com.mapper.UserMapper;
import com.service.AuthService;
import com.utils.JwtUtils;
import com.utils.PasswordEncoderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        LoginResponse response = new LoginResponse();
        
        try {
            // 根据用户名查询用户
            User user = userMapper.selectByUsername(loginRequest.getUsername());
            
            // 验证用户是否存在以及密码是否正确
            if (user == null || !PasswordEncoderUtil.matches(loginRequest.getPassword(), user.getPassword())) {
                response.setSuccess(false);
                response.setMessage("用户名或密码错误");
                return response;
            }
            
            // 更新用户最后登录时间
            userMapper.updateLastLoginTime(user.getId());
            
            // 生成JWT令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            claims.put("username", user.getUsername());
            claims.put("role", user.getRole());
            String token = JwtUtils.generateJwt(claims);
            
            // 构建响应
            response.setSuccess(true);
            response.setToken(token);
            response.setUsername(user.getUsername());
            response.setRole(user.getRole());
            response.setUserId(user.getId());
            response.setMessage("登录成功");
            
        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage("登录失败，请稍后重试");
            e.printStackTrace();
        }
        
        return response;
    }
}